#include "stdio.h"
#include "string.h"

#include "config.h"
#include "publish.h"

static short FramePubId = 1;//报文标识符
//获得报文标识符
int publish_get_frame_id()
{
    return FramePubId;
}


int publish_publish_topic(int qos,int sockfd)
{
	unsigned char frame[MAX_SEND_BUFF_SIZE];
	int frameLen = 0;
	int remainLen = 0;
	unsigned char offset=0;

	char *msg = config_get_cur_time();//发布内容为当前时间

	if(sockfd == -1)
	{
		printf("%s():invalid socket\n",__func__);
		return -1;
	}

	memset(frame,0,sizeof(frame));    

	//printf("%s():start\n",__func__);

	//bit[4-7]:消息类型
	//bit[3]:dup
	//bit[1-2]:qos等级
	//bit[0]:retain
    frame[0] = MQTT_MSG_PUBLISH;
	if(qos && qos<3)
	{
		frame[0] |= (qos<<1);
	}
	remainLen = strlen(TOPIC_PUBLISH)+strlen(msg)+2;//主题长度+主题+主题内容

	// Remaining Length，剩余长度
	if (remainLen <= 127) 
	{
	   frame[1] = remainLen;
	   offset=2;
	} 
	else 
	{
	   // first byte is remainder (mod) of 128, then set the MSB to indicate more bytes
	   frame[1] = remainLen % 128;
	   frame[1] = frame[1] | 0x80;
	   // second byte is number of 128s
	   frame[2] = remainLen / 128;
		offset=3;
	}

	frame[offset++] = (strlen(TOPIC_PUBLISH)>>8);
	frame[offset++] = (strlen(TOPIC_PUBLISH)&0XFF);

	memcpy(&frame[offset],TOPIC_PUBLISH,strlen(TOPIC_PUBLISH));
	offset+=strlen(TOPIC_PUBLISH);

	if(qos == 1 || qos == 2)//如果消息等级为1或者2,应加上报文标识符
	{
		frame[offset++] = (FramePubId>>8);
		frame[offset++] = (FramePubId&0XFF);
	}

	memcpy(&frame[offset],msg,strlen(msg));
	offset+=strlen(msg);

	//printf("publish_publish_topic():packlen is %d\n",offset);
	//config_printf_hex(frame,offset);

	printf("publish_publish_topic():publish topic:%s\n",TOPIC_PUBLISH);
	printf("publish_publish_topic():publish topicMsg:%s\n",msg);

    return (config_mqtt_write(sockfd,frame,offset));
}